package com.xunyin.modules.wechatshop.rest;


import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.common.bean.LocalUser;
import com.xunyin.common.interceptor.AuthCheck;
import com.xunyin.enums.RefundStatusEnum;
import com.xunyin.modules.mtorder.service.MtOrderService;
import com.xunyin.modules.mtrefund.domain.MtRefund;
import com.xunyin.modules.mtrefund.service.RefundService;
import com.xunyin.modules.mtrefund.service.dto.RefundDto;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.YxUserService;
import com.xunyin.modules.user.service.dto.UserOrderDto;
import com.xunyin.utils.StringUtil;
import com.xunyin.web.ResponseObject;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;



/**
 * 售后类controller
 * Copyright (C) 2022-2023
 * All rights reserved, Designed By www.tonetn.com
 * 注意：
 * 本软件为讯音云商开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
@Slf4j
@RestController
@Api(value = "商城订单售后相关接口", tags = "共享空间:商城订单售后相关接口")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientRefundController {

    private final YxUserService userService;

    /**
     * 售后服务接口
     * */
    @Autowired
    private RefundService refundService;

    /**
     * 订单服务接口
     * */
    @Autowired
    private MtOrderService orderService;

    /**
     * 获取售后订单列表
     */
    @RequestMapping(value = "/refund/list", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Object> list(HttpServletRequest request, @RequestParam Map<String, Object> param){
/*        String token = request.getHeader("Access-Token");
        UserInfo userInfo = TokenUtil.getUserInfoByToken(token);

        if (userInfo == null) {
            return getFailureResult(1001, "用户未登录");
        }*/

        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }

        param.put("userId", user.getUid().intValue());

        String status = param.get("status") != null ? param.get("status").toString() : "";
        if (status.equals("1")) {
            status = RefundStatusEnum.CREATED.getKey();
        } else {
            status = "";
        }
        Map<String, Object> params = new HashMap();
        params.put("userId", user.getUid().intValue());
        if (StringUtil.isNotEmpty(status)) {
            params.put("status", status);
        }
        params.put("pageNumber", param.get("page").toString());

        ResponseObject orderData = refundService.getUserRefundList(params);
        return ApiResult.ok(orderData.getData());
        //return getSuccessResult(orderData.getData());
    }

    /**
     * 售后订单提交
     */
    @RequestMapping(value = "/refund/submit", method = RequestMethod.POST)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Map<String, Object>> submit(HttpServletRequest request, @RequestBody Map<String, Object> param) {

        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }

        param.put("userId", user.getUid().intValue());

        String orderId = param.get("orderId") == null ? "" : param.get("orderId").toString();
        String remark = param.get("remark") == null ? "" : param.get("remark").toString();
        String type = param.get("type") == null ? "" : param.get("type").toString();
        String images = param.get("images") == null ? "" : param.get("images").toString();

        UserOrderDto order = orderService.getOrderById(Integer.parseInt(orderId));

        if (order == null || (!order.getUserId().equals(user.getUid().intValue()))) {
            throw new XunyinException("用户与订单的用户不匹配");
            //user.getUid().intValue()
            //return getFailureResult(2001);
        }

        RefundDto refundDto = new RefundDto();
        refundDto.setUserId(user.getUid().intValue());
        refundDto.setOrderId(order.getId());
        refundDto.setRemark(remark);
        refundDto.setType(type);
        if (order.getStoreInfo() != null) {
            refundDto.setStoreId(order.getStoreInfo().getId());
        }
        refundDto.setAmount(order.getPayAmount());
        refundDto.setImages(images);
        MtRefund refundInfo = refundService.createRefund(refundDto);

        Map<String, Object> outParams = new HashMap();
        outParams.put("refundInfo", refundInfo);

        //ResponseObject responseObject = getSuccessResult(outParams);

        //return getSuccessResult(responseObject.getData());
        return ApiResult.ok(outParams);
    }

    /**
     * 获取售后订单详情
     */
    @RequestMapping(value = "/refund/detail", method = RequestMethod.GET)
    @CrossOrigin
    @AuthCheck
    public ApiResult<Map<String, Object>> detail(HttpServletRequest request){
/*        String token = request.getHeader("Access-Token");
        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);

        if (mtUser == null) {
            return getFailureResult(1001, "用户未登录");
        }*/
        Long uid = LocalUser.getUser().getUid();
        YxUser user = userService.getById(uid.intValue());
        if (user == null) {
            throw new XunyinException("用户未登录");
        }
        String refundId = request.getParameter("refundId");
        if (StringUtil.isEmpty(refundId)) {
            throw new XunyinException("售后订单ID不能为空");
            //return getFailureResult(2000, "售后订单ID不能为空");
        }

        RefundDto refundInfo = refundService.getRefundById(Integer.parseInt(refundId));
        Map<String, Object> outParams = new HashMap();
        outParams.put("refundInfo", refundInfo);
        return ApiResult.ok(outParams);
        //return getSuccessResult(refundInfo);
    }
}
